<!DOCTYPE html>


<html lang="zh-Hans">


<head>
  <meta charset="utf-8" />
   
  <meta name="keywords" content="代码,生活,杂记,思考" />
   
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    JS垃圾回收机制 |  AURORA
  </title>
  <meta name="generator" content="hexo-theme-ayer">
  
  <link rel="shortcut icon" href="/favicon.ico" />
  
  
<link rel="stylesheet" href="/dist/main.css">

  
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css">

  
<link rel="stylesheet" href="/css/custom.css">

  
  
<script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>

  
  

  

<link rel="alternate" href="/atom.xml" title="AURORA" type="application/atom+xml">
</head>

</html>

<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-JS垃圾回收机制"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  JS垃圾回收机制
</h1>
 

    </header>
     
    <div class="article-meta">
      <a href="/2020/03/09/JS%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6%E6%9C%BA%E5%88%B6/" class="article-date">
  <time datetime="2020-03-08T16:00:00.000Z" itemprop="datePublished">2020-03-09 00:03:00</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/%E6%8A%80%E6%9C%AF/">技术</a> / <a class="article-category-link" href="/categories/%E6%8A%80%E6%9C%AF/%E5%89%8D%E7%AB%AF/">前端</a> / <a class="article-category-link" href="/categories/%E6%8A%80%E6%9C%AF/%E5%89%8D%E7%AB%AF/JavaScript/">JavaScript</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> Word count:</span>
            <span class="post-count">2.8k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> Reading time≈</span>
            <span class="post-count">10 min</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <h1 id="序言"><a href="#序言" class="headerlink" title="序言"></a>序言</h1><p>一般的浏览器都具有Javascript垃圾回收机制（GC：Garbage Collection），也就是说执行环境会负责管理代码执行过程中使用的内存，这个过程是不可见的，我们创建的基本类型，函数，对象，数组等等，都需要内存，同时也都需要回收</p>
<p>当不再需要某样东西时，javascript引擎就会发现并清理它，具体是怎么实现的呢？</p>
<a id="more"></a>
<h1 id="可达性"><a href="#可达性" class="headerlink" title="可达性"></a>可达性</h1><p>JS管理内存有一个主要概念就是可达性。<br>简单来说，可达性就是可以以某种方法访问或引用的值，他们被保证存储在内存中。</p>
<h2 id="根——固定的可达值，永远不会被回收"><a href="#根——固定的可达值，永远不会被回收" class="headerlink" title="根——固定的可达值，永远不会被回收"></a>根——固定的可达值，永远不会被回收</h2><ul>
<li>本地函数的局部变量与参数</li>
<li>当前调用函数的作用域链上的变量与参数</li>
<li>全局变量</li>
</ul>
<h2 id="如果引用或引用链可以从根访问到其他任何值，则认为该值是可以访问的"><a href="#如果引用或引用链可以从根访问到其他任何值，则认为该值是可以访问的" class="headerlink" title="如果引用或引用链可以从根访问到其他任何值，则认为该值是可以访问的"></a>如果引用或引用链可以从根访问到其他任何值，则认为该值是可以访问的</h2><p>例如，如果局部变量中有对象，并且该对象具有引用另一个对象的属性，则该对象被视为可达性， 它引用的那些也是可以访问的</p>
<h3 id="一个例子"><a href="#一个例子" class="headerlink" title="一个例子"></a>一个例子</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> user = &#123;</span><br><span class="line">	name:<span class="string">'tom'</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><img src="https://img-blog.csdnimg.cn/20200309092249872.png" alt=""><br>需要注意的是，这里需要转变一下观念，代码里的user和 <code>{name:“John”}</code>，实际上是两个对象，而这里的箭头，指的就是user引用了对象 <code>{name:“John”}</code>。</p>
<p>这个时候如果user的值被覆盖，引用丢失：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">user = <span class="literal">null</span></span><br></pre></td></tr></table></figure>
<p><img src="https://img-blog.csdnimg.cn/20200309092555316.png" alt=""><br>那么很显然， <code>{name:“John”}</code>将没有任何办法能够引用和访问到它，垃圾回收将丢弃这个对象并释放内存</p>
<h3 id="两个引用"><a href="#两个引用" class="headerlink" title="两个引用"></a>两个引用</h3><p>而对于下面这个例子</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> user = &#123;</span><br><span class="line">	name:<span class="string">'tom'</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> admin = user</span><br><span class="line">user = <span class="literal">null</span></span><br></pre></td></tr></table></figure>
<p><img src="https://img-blog.csdnimg.cn/2020030909322959.png" alt=""><br>最终该对象是可以通过admin全局变量访问的，所以即使user被覆盖，也依然可以通过admin访问，对象可达，所以不会被回收</p>
<h3 id="相互关联"><a href="#相互关联" class="headerlink" title="相互关联"></a>相互关联</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">marry</span> (<span class="params">man, woman</span>) </span>&#123;</span><br><span class="line">  woman.husban = man;</span><br><span class="line">  man.wife = woman;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    father: man,</span><br><span class="line">    mother: woman</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> family = marry(&#123;</span><br><span class="line">  name: <span class="string">"John"</span></span><br><span class="line">&#125;, &#123;</span><br><span class="line">  name: <span class="string">"Ann"</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>函数 marry 通过给两个对象<strong>彼此提供引用</strong>来“联姻”它们，并返回一个包含两个对象的新对象，这个时候他们的内存结构是这样的：<br><img src="https://img-blog.csdnimg.cn/2020030909594076.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTIwMzE5NTg=,size_16,color_FFFFFF,t_70" alt=""><br>到目前为止所有对象都是可以访问的</p>
<p>这个时候删除两个引用：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">family.father = <span class="literal">null</span></span><br><span class="line">family.mother.husband = <span class="literal">null</span></span><br></pre></td></tr></table></figure>
<p><img src="https://img-blog.csdnimg.cn/20200309100208113.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTIwMzE5NTg=,size_16,color_FFFFFF,t_70" alt=""></p>
<p>这个时候我们发现，已经没有任何方法途径可以访问和引用左下角的这个对象了：</p>
<p><img src="https://img-blog.csdnimg.cn/20200309100250626.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTIwMzE5NTg=,size_16,color_FFFFFF,t_70" alt=""><br>垃圾回收后：</p>
<p><img src="https://img-blog.csdnimg.cn/20200309100445853.png" alt=""></p>
<h3 id="无法访问的数据块"><a href="#无法访问的数据块" class="headerlink" title="无法访问的数据块"></a>无法访问的数据块</h3><p>有可能整个相互连接的对象变得不可访问并从内存中删除。<br>例如上面的例子：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">family = <span class="literal">null</span></span><br></pre></td></tr></table></figure>
<p>这个时候内存的结构变成了：<br><img src="https://img-blog.csdnimg.cn/20200309100642174.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTIwMzE5NTg=,size_16,color_FFFFFF,t_70" alt=""><br>由于family对象已经从根上断开了连接，所以marry函数内部的变量，参数都会被删除</p>
<h1 id="垃圾回收算法"><a href="#垃圾回收算法" class="headerlink" title="垃圾回收算法"></a>垃圾回收算法</h1><p>一般来说<strong>没有被引用的对象就是垃圾</strong>，就是要被清除， 有个例外<strong>如果几个对象引用形成一个环，互相引用，但根访问不到它们，这几个对象也是垃圾</strong>，也要被清除。</p>
<h2 id="标记清除"><a href="#标记清除" class="headerlink" title="标记清除"></a>标记清除</h2><p>这是一个最常用的回收算法，定期执行以下垃圾回收步骤：</p>
<ul>
<li>垃圾回收器获取<strong>根</strong>并<strong>“标记”</strong>他们</li>
<li>然后访问并“标记”所有他们的引用</li>
<li>然后它访问标记的对象并标记它们的引用。所有被访问的对象都被记住，以便以后不再访问同一个对象两次。</li>
<li>以此类推，直到有未访问的引用(可以从根访问)为止。</li>
<li>除标记的对象外，所有对象都被删除。</li>
</ul>
<p>举个例子，现有一个对象结构如下：<br><img src="https://img-blog.csdnimg.cn/20200309102706389.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTIwMzE5NTg=,size_16,color_FFFFFF,t_70" alt=""></p>
<p><strong>第一步：标记根</strong><br><img src="https://img-blog.csdnimg.cn/20200309102734118.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTIwMzE5NTg=,size_16,color_FFFFFF,t_70" alt=""><br>第二步：标记他们的引用<br><img src="https://img-blog.csdnimg.cn/20200309102752568.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTIwMzE5NTg=,size_16,color_FFFFFF,t_70" alt=""><br>第三步：以此类推，标记子孙代的引用：<br><img src="https://img-blog.csdnimg.cn/20200309102828827.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTIwMzE5NTg=,size_16,color_FFFFFF,t_70" alt=""><br>第四步：没有被标记的对象被清除</p>
<h2 id="引用计数"><a href="#引用计数" class="headerlink" title="引用计数"></a>引用计数</h2><p>引用计数的含义是跟踪记录每个值被引用的次数。</p>
<p>当声明了一个变量并将一个引用类型值赋给该变量时，则这个值的引用次数就是 1。如果同一个值又被赋给另一个变量，则该值的引用次数加 1。相反，如果包含对这个值引用的变量又取得了另外一个值，则这个值的引用次数减 1。当这个值的引用次数变成 0 时，则说明没有办法再访问这个值了，因而就可以将其占用的内存空间回收回来。</p>
<p>这样，当垃圾回收器下次再运行时，它就会释放那些引用次数为 0 的值所占用的内存。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">test</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> a = &#123;&#125;;    <span class="comment">// &#123;&#125;的引用次数为1</span></span><br><span class="line">    <span class="keyword">var</span> b = a;     <span class="comment">// &#123;&#125;的引用次数加1，为2</span></span><br><span class="line">    <span class="keyword">var</span> c = a;     <span class="comment">// &#123;&#125;的引用次数再加1，为3</span></span><br><span class="line">    <span class="keyword">var</span> b = &#123;&#125;;    <span class="comment">// &#123;&#125;的引用次数减1，为2</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>其实读者在看完上面这段描述，再结合标记清除，很快就会发现，引用计数对于那种相互引用产生的数据块会产生严重的问题：他们的引用数量永远不会是0</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">fn</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> a = &#123;&#125;;</span><br><span class="line">    <span class="keyword">var</span> b = &#123;&#125;;</span><br><span class="line">    a.pro = b;</span><br><span class="line">    b.pro = a;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>正如上面这个例子所说，他们之间的内存结构如下：</p>
<p><img src="https://img-blog.csdnimg.cn/20200309104540572.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTIwMzE5NTg=,size_16,color_FFFFFF,t_70" alt=""><br>当函数执行完毕或者说直接就没有执行时：a与b的引用次数都不为0，但是他们整体的代码块是不可达的，所以可以使用标记清除来回收他们的内存，可是引用计数就束手无策了。</p>
<p>如果使用引用计数，当fn函数被大量调用，可以想象，其内存占用将直线上升</p>
<p>虽然在如今的浏览器中基本都是使用标记清除，但是！！！IE这个奇葩又来了……..</p>
<p>IE 中有一部分对象并不是原生 JS 对象。例如，其内存泄露 DOM 和 BOM 中的对象就是使用 C++ 以 COM 对象的形式实现的，而 COM 对象的垃圾回收机制采用的就是引用计数策略。因此，<strong>即使IE的js引擎采用标记清除策略来实现，但 JS 访问的COM对象依然是基于引用计数策略的</strong>。<strong>换句话说，只要在 IE 中涉及 COM 对象，就会存在循环引用的问题</strong>。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> element = <span class="built_in">document</span>.getElementById(<span class="string">"some_element"</span>);</span><br><span class="line"><span class="keyword">var</span> myObject = <span class="keyword">new</span> <span class="built_in">Object</span>();</span><br><span class="line">myObject.e = element;</span><br><span class="line">element.o = myObject;</span><br></pre></td></tr></table></figure>
<p>这个例子在一个 DOM 元素 element 与一个原生js对象 myObject 之间创建了循环引用。其中，变量 myObject 有一个属性 e 指向 element 对象；而变量 element 也有一个属性 o 回指 myObject。由于存在这个循环引用，即使例子中的 DOM 从页面中移除，它也永远不会被回收。</p>
<h1 id="两个实际性的例子："><a href="#两个实际性的例子：" class="headerlink" title="两个实际性的例子："></a>两个实际性的例子：</h1><p><strong>第一个：</strong><br><img src="https://imgconvert.csdnimg.cn/aHR0cHM6Ly9zZWdtZW50ZmF1bHQuY29tL2ltZy9yZW1vdGUvMTQ2MDAwMDAyMDMzODU1MQ?x-oss-process=image/format,png" alt=""></p>
<ul>
<li>黄色是指直接被 js变量所引用，在内存里</li>
<li>红色是指由于DOM树的连接关系，间接被 js变量所引用，如上图，<strong>refB 被 refA 间接引用，导致即使 refB 变量被清空，也是不会被回收的</strong></li>
<li>子元素 refB 由于 <strong>parentNode指针</strong> 的间接引用，只要它不被删除，它所有的父元素（图中红色部分）都不会被删除</li>
<li>换句话说：要将上面有颜色的块删除，<strong>必须同时删除refA和refB</strong>，否则都不行</li>
</ul>
<p><strong>第二个（这个例子简直——绝了，我都惊呆了）</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">window</span>.onload=<span class="function"><span class="keyword">function</span> <span class="title">outerFunction</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> obj = <span class="built_in">document</span>.getElementById(<span class="string">"element"</span>);</span><br><span class="line">    obj.onclick=<span class="function"><span class="keyword">function</span> <span class="title">innerFunction</span>(<span class="params"></span>)</span>&#123;&#125;;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>这段代码看起来没什么问题，但是 obj 引用了 document.getElementById(‘element’)，而 document.getElementById(‘element’) 的 onclick 方法会引用外部环境中的变量（outerFunction），自然也包括 obj，obj又引用了document.getElementById(‘element’) 。<br>是不是很隐蔽啊。(在比较新的浏览器中在移除Node的时候已经会移除其上的event了，但是在老的浏览器，特别是 IE 上会有这个 bug)</p>
<p>解决办法：</p>
<p>最简单的方式就是自己手工解除循环引用，比如刚才的函数可以这样</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">window</span>.onload=<span class="function"><span class="keyword">function</span> <span class="title">outerFunction</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> obj = <span class="built_in">document</span>.getElementById(<span class="string">"element"</span>);</span><br><span class="line">    obj.onclick=<span class="function"><span class="keyword">function</span> <span class="title">innerFunction</span>(<span class="params"></span>)</span>&#123;&#125;;</span><br><span class="line">    obj=<span class="literal">null</span>;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>终于：IE9+ 并不存在循环引用导致 DOM 内存泄露问题，可能是微软做了优化，或者 DOM 的回收方式已经改变。</p>
<h1 id="垃圾回收的触发时机："><a href="#垃圾回收的触发时机：" class="headerlink" title="垃圾回收的触发时机："></a>垃圾回收的触发时机：</h1><p>垃圾回收器周期性运行，如果分配的内存非常多，那么回收工作也会很艰巨，确定垃圾回收时间间隔就变成了一个值得思考的问题。<strong>IE6的垃圾回收是根据内存分配量运行的，当环境中存在256个变量、4096个对象、64k的字符串任意一种情况的时候就会触发垃圾回收器工作</strong>，看起来很科学，不用按一段时间就调用一次，有时候会没必要，这样按需调用不是很好吗？但是如果环境中就是有这么多变量等一直存在，现在脚本如此复杂，很正常，那么结果就是垃圾回收器一直在工作，这样浏览器就没法儿玩儿了。</p>
<p>微软在 IE7 中做了调整，触发条件不再是固定的，而是动态修改的，初始值和 IE6 相同，如果垃圾回收器回收的内存分配量低于程序占用内存的15%，说明大部分内存不可被回收，设的垃圾回收触发条件过于敏感，这时候把临街条件翻倍，如果回收的内存高于 85%，说明大部分内存早就该清理了，这时候把触发条件置回。这样就使垃圾回收工作智能了很多</p>
<h1 id="GC优化策略"><a href="#GC优化策略" class="headerlink" title="GC优化策略"></a>GC优化策略</h1><h2 id="分代回收"><a href="#分代回收" class="headerlink" title="分代回收"></a>分代回收</h2><p>这个和Java回收策略思想是一致的，也是V8所主要采用的。目的是通过区分“<strong>临时</strong>”与“<strong>持久</strong>”对象；<strong>多回收“临时对象”区</strong>（young generation），<strong>少回收“持久对象”区</strong>（tenured generation），减少每次需遍历的对象，从而减少每次GC的耗时。如图：<br>一些优化：<br><img src="https://img-blog.csdnimg.cn/20200309112821191.png" alt=""></p>
<h2 id="增量回收"><a href="#增量回收" class="headerlink" title="增量回收"></a>增量回收</h2><p>这个方案的思想很简单，就是“每次处理一点，下次再处理一点，如此类推”。如图：<br><img src="https://img-blog.csdnimg.cn/20200309113237406.png" alt=""></p>
<h2 id="空闲时间收集"><a href="#空闲时间收集" class="headerlink" title="空闲时间收集"></a>空闲时间收集</h2><p>垃圾回收器只在 CPU 空闲时运行，以减少对执行的可能影响。</p>
<h1 id="内存溢出带来的影响"><a href="#内存溢出带来的影响" class="headerlink" title="内存溢出带来的影响"></a>内存溢出带来的影响</h1><p>JS 程序的内存溢出后，会使某一段函数体永远失效（取决于当时的 JS 代码运行到哪一个函数），通常表现为程序突然卡死或程序出现异常。</p>
<h2 id="可能的泄露点"><a href="#可能的泄露点" class="headerlink" title="可能的泄露点"></a>可能的泄露点</h2><ul>
<li>DOM/BOM 对象泄漏；</li>
<li>script 中存在对 DOM/BOM 对象的引用导致；</li>
<li>JS 对象泄漏；</li>
<li>通常由闭包导致</li>
<li>事件处理回调，导致 DOM 对象和脚本中对象双向引用，这个是常见的泄漏原因；</li>
</ul>
<h2 id="代码关注点"><a href="#代码关注点" class="headerlink" title="代码关注点"></a>代码关注点</h2><ul>
<li>DOM 中的 addEventLisner 函数及派生的事件监听</li>
<li>其它 BOM 对象的事件监听， 比如 websocket 实例的 on 函数;</li>
<li>避免不必要的函数引用；</li>
<li>如果使用 render 函数，避免在 HTML 标签中绑定 DOM/BOM 事件;</li>
</ul>
 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>Copyright： </strong>
          Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2020/03/10/%E5%9C%A3%E6%9D%AF%E5%B8%83%E5%B1%80%E4%B8%8E%E5%8F%8C%E9%A3%9E%E7%BF%BC%E5%B8%83%E5%B1%80/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            圣杯布局与双飞翼布局
          
        </div>
      </a>
    
    
      <a href="/2020/03/09/animation-timing-function/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">animation-timing-function</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "2eBxdPB3eEwraN7IpwFckzeL-gzGzoHsz",
    app_key: "VGgCefQEluVxHdyMsm1Dpeih",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "评论一下我的文章吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2015-2020
        <i class="ri-heart-fill heart_icon"></i> AURORA_ZXH
      </li>
    </ul>
    <ul>
      <li>
        
        
        
        Powered by <a href="https://hexo.io" target="_blank">Hexo</a>
        <span class="division">|</span>
        Theme - <a href="https://github.com/Shen-Yu/hexo-theme-ayer" target="_blank">Ayer</a>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>Visitors:<span id="busuanzi_value_site_uv"></span></s>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>Views:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
      </li>
    </ul>
  </div>
</footer>
      <div class="float_btns">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

      </div>
    </main>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/avatar.jpg" alt="AURORA"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="http://aurora-zxh.lofter.com/" target="_blank" rel="noopener">随记</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/about">关于我</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/link">友链</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="Search">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <script>
      if (window.matchMedia("(max-width: 768px)").matches) {
        document.querySelector('.content').classList.remove('on');
        document.querySelector('.sidebar').classList.remove('on');
      }
    </script>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="/images/alipay.png">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="/images/wxpay.png">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
    
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->


<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: 'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto'
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->

<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>

<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->


<script src="/js/busuanzi-2.3.pure.min.js"></script>


<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->


<link rel="stylesheet" href="/css/clipboard.css">

<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>


<!-- CanvasBackground -->


    
  </div>
</body>

</html>